<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <h1 class="centered-text">飞检考试须知</h1>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
      </div>
      <div class="centered-text">
        <div class="center">
          <span class="left-span">1.飞检考试时间为75分钟,答完题可以点击“提交”,超出时间则自动交</span><br />
          <span class="left-span">卷；</span><br />

          <span class="left-span">2.考试采用100制,选择题数为6道,每题5分,填空题为6道,每题5分,简答</span><br />
          <span class="left-span">题为2题,每题20分;</span><br />

          <span class="left-span">3.每人有三次考试机会(初试一次和补考两次),考试90分及格。三次不</span><br />
          <span class="left-span">过者,当月绩效评价降低;</span><br />

          <span class="left-span">4.考试开始后不得交头接耳,翻看sop,违者不及格处理;</span><br />

          <span class="left-span">5.考试范围:2道运维技术选择题+4道运维手册选择题+6道运维手册填</span><br />
          <span class="left-span">空题+2道简答题;</span><br />

        </div>
      </div>
    </el-card>

    <el-card>
      <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName">
        <el-table-column label="#" width="50">
          <template slot-scope="scope">
            {{
              (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="科目名称" width="300">
        </el-table-column>
        <el-table-column prop="desc" label="科目详情">
        </el-table-column>
        <el-table-column prop="edit" label="操作栏" width="600">
          <template slot-scope="scope">
            <template v-if="scope.row.total_show === 0">
              <el-button v-if="scope.row.next_paper === 0" type="primary" @click="startExam(scope.row.id)">开始考试</el-button>
              <el-button v-else-if="scope.row.next_paper === 1" type="primary"
                @click="startExam(scope.row.id)">补考1</el-button>
              <el-button v-else-if="scope.row.next_paper === 2" type="primary"
                @click="startExam(scope.row.id)">补考2</el-button>
              <el-button v-else type="danger">很遗憾本次考试未通过</el-button>
            </template>
            <template v-else-if="scope.row.total_show === 1" slot-scope="scope">
              <el-button type="primary">恭喜通过本次考试</el-button>
            </template>
            <template v-else-if="scope.row.total_show === 2" slot-scope="scope">
              <el-button type="primary">批改中</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo" :page-sizes="[5, 10, 50, 100]" :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <!-- 弹出考试框 -->
    <el-dialog :visible.sync="dialogFormVisible" :fullscreen="true" :close-on-click-modal="false" :show-close="false">
      <template v-slot:title>
        <div style="text-align: center; position: fixed; width: 100%; padding: 0px; top: 0;">
          <h1>{{ examForm.title }}</h1>
          <p>考生姓名:{{ nick_name }}</p>
          <p>考试倒计时: {{ minutes }} 分 {{ seconds }} 秒</p>
        </div>
      </template>
      <el-form :model="examForm" style="margin-top: 80px;">
        <h2>1、选择题。(一共6题,每题5分)</h2>
        <div v-for="(option, index) in examForm.other_paper_list">
          <!-- 单选 -->
          <div v-if="option.questionType == 'xz'">
            <h3>{{ index + 1 }}.({{ option.question_type_ch }}){{ option.content }}</h3>
            <el-radio-group v-model="option.examinee_answer">
              <el-radio label="A">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option" @click.stop.prevent>{{ option.choice_a }}</p>
                </div>
              </el-radio><br>
              <el-radio label="B">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_b }}</p>
                </div>
              </el-radio><br>
              <el-radio label="C">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_c }}</p>
                </div>
              </el-radio><br>
              <el-radio label="D">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_d }}</p>
                </div>
              </el-radio>
            </el-radio-group>
          </div>
          <!-- 多选 -->
          <div v-else-if="option.questionType == 'mxz'">
            <h3>{{ index + 1 }}.({{ option.question_type_ch }}){{ option.content }}</h3>
            <el-checkbox-group v-model="option.examinee_answers">
              <el-checkbox label="A">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_a }}</p>
                </div>
              </el-checkbox><br>
              <el-checkbox label="B">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_b }}</p>
                </div>
              </el-checkbox><br>
              <el-checkbox label="C">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_c }}</p>
                </div>
              </el-checkbox><br>
              <el-checkbox label="D">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_d }}</p>
                </div>
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div class="no-copy-paste">
          <h2>2、填空题。(一共6题,每题5分)</h2>
          <div v-for="(question_now, index) in examForm.tk_paper_list" :key="index" id="box1">
            <p style="display: inline-block; vertical-align: middle">
              {{ index + 1 }}.({{ "填空" }})
            </p>
            <input v-model="question_now.id" type="hidden">
            <input v-model="question_now.tk_num" type="hidden">
            <template v-for="(question, qIndex) in question_now.blanks">
              <template v-if="question.type === 'text'">
                {{ question.value }}
              </template>
              <template v-else-if="question.type === 'input'">
                <span :id="`${question_now.id}_${qIndex}`" v-if="is_super === 0" @copy="preventCopyPaste"
                  @paste="preventCopyPaste"
                  style="width: 200px; height: 24px; line-height: 24px; font-size: 20px; padding: 1px 14px; border-bottom: 1px solid black; color: red"
                  contenteditable="true" @input="handleSpanInput(question_now.id, qIndex, $event)">
                  &nbsp;&nbsp;
                </span>
                <span :id="`${question_now.id}_${qIndex}`" v-else
                  style="width: 200px; height: 24px; line-height: 24px; font-size: 20px; padding: 1px 14px; border-bottom: 1px solid black; color: red"
                  contenteditable="true" @input="handleSpanInput(question_now.id, qIndex, $event)">
                  &nbsp;&nbsp;
                </span>
              </template>
            </template>
          </div>
        </div>
        <div class="no-copy-paste">
          <h2>3、简答题。(一共2题,每题20分)</h2>
          <div v-for="(jd, jdIndex) in examForm.jd_paper_list" :key="jdIndex">
            <h3>{{ jdIndex + 1 }}.({{ "简答" }}){{ jd.content }}</h3>
            <!-- <el-input  v-model="jd.jd_examinee_answer" type="textarea" placeholder="请填写答案"></el-input> -->
            <textarea v-model="jd.jd_examinee_answer" rows="30" cols="100" v-if="is_super === 0" @copy="preventCopyPaste"
              @paste="preventCopyPaste" style="color: red"></textarea>
            <textarea v-model="jd.jd_examinee_answer" rows="30" cols="100" v-else style="color: red"></textarea>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" style="position: fixed; bottom: 10px; width: 100%;">
        <!-- <el-button @click="dialogFormVisible = false">取 消</el-button> -->
        <div style="text-align: center;">
          <el-button type="primary" @click="submitExam" style="width: 150px;">交 卷</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import testApi from '@/api/testMange';
import { mapGetters } from 'vuex';
export default {
  mounted() {
    // 在组件挂载时添加事件监听器
    window.addEventListener('beforeunload', this.beforeUnloadHandler);
  },
  beforeDestroy() {
    // 在组件销毁前移除事件监听器
    window.removeEventListener('beforeunload', this.beforeUnloadHandler);
  },
  methods: {
    beforeUnloadHandler(event) {
      // 在页面即将关闭时的处理逻辑
      event.preventDefault(); // 用于标识事件已被处理，浏览器会弹出提示框
      event.returnValue = '确定要离开吗？';
    },
    preventCopyPaste(event) {
      // 阻止复制和粘贴事件
      event.preventDefault();
      this.$message.warning('禁止复制和粘贴操作');
    },
    // handleOptionClick(option, selectedOption) {
    //   // 在这里执行赋值逻辑,selectedOption 就是选中的选项值
    //   option.examinee_answers = selectedOption;
    //   // 或者其他你需要执行的逻辑
    // },
    handleSpanInput(id, qIndex, event) {
      const inputValue = event.target.innerText;
      // 将输入值传递到后端或在需要的地方进行处理
      // 在这里你可以更新相应的数据结构或进行其他操作
      // console.log(`ID: ${id}, Question Index: ${qIndex}, Input Value: ${inputValue}`);
      // 找到对应的 tks 对象和输入框
      const tk = this.examForm.tk_paper_list.find(tk => tk.id === id);
      if (tk) {
        const input = tk.blanks.find((blank, index) => index === qIndex && blank.type === 'input');
        if (input) {
          input.value = inputValue;
        }
        // 更新 tks 对象，确保 Vue 响应式更新
        this.$set(this.examForm.tk_paper_list, this.examForm.tk_paper_list.indexOf(tk), { ...tk });
      }
    },
    startCountdown() {
      this.countdownTimer = setInterval(() => {
        if (this.examForm.countdown > 0) {
          this.examForm.countdown--;
        } else if (this.examForm.countdown == -1) {

        } else {
          // 提交表单到后台
          testApi.submitFlyExam(this.examForm).then((reponse) => {
            this.examForm.tk_paper_list = []; // 清空填空题数据
            // 关闭弹窗
            this.dialogFormVisible = false;
            // 提示提交成功
            this.$message({
              message: reponse.message,
              type: "success",
            });
          });
          // 在计时结束后执行相应操作,例如关闭对话框
          this.dialogFormVisible = false;
          clearInterval(this.countdownTimer);
          // 刷新页面
          // this.getExamTitleList();
        }
      }, 1000);
    },
    submitExam() {
      // console.log('Submit button clicked!');
      let isValid = true;
      // 遍历题目校验
      // this.examForm.options.forEach(option => {
      //   if (!option.examinee_answer && option.examinee_answers.length === 0) {
      //     // 选项没有值  
      //     isValid = false;
      //     return false;
      //   }
      // })
      // // 遍历 tks 进行判断
      // this.examForm.tks.forEach((tk) => {
      //   tk.blanks.forEach((blank) => {
      //     if (blank.type === 'input' && blank.value.trim() === '') {
      //       // 如果发现有空值，将 isValid 设置为 false
      //       isValid = false;
      //     }
      //   });
      // });
      // // 遍历jds校验
      // this.examForm.jds.forEach(jd => {
      //   if (!jd.jd_examinee_answer) {
      //     // 选项没有值  
      //     isValid = false;
      //     return false;
      //   }
      // })

      // 提交其他逻辑
      if (isValid) {
        // 通过验证
        // 提交表单到后台
        testApi.submitFlyExam(this.examForm).then((reponse) => {
          this.examForm.tk_paper_list = []; // 清空填空题数据
          // 关闭弹窗
          this.dialogFormVisible = false;
          // 提示提交成功
          this.$message({
            message: reponse.message,
            type: "success",
          });
          this.getExamTitleList();
        });
      } else {
        // 失败 
        this.$message({
          message: "有题目未作答,请仔细检查！！！",
          type: "error",
        });
        console.log("error submit!!");
        return false;
      }
    },
    startExam(id) {
      testApi.startExamById(id).then((response => {
        this.examForm = response.data;
      }))
      this.dialogFormVisible = true;
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },
    getExamTitleList() {
      testApi.getExamTitleList(this.searchModel).then((response) => {
        this.total = response.data.total;
        this.tableData = response.data.exam_title;
      });
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.getExamTitleList();
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo;
      this.getExamTitleList();
    },
  },
  created() {
    this.getExamTitleList();
  },
  computed: {
    ...mapGetters([
      // 'name',
      'is_super',
      'nick_name'
    ]),
    minutes() {
      return Math.floor(this.examForm.countdown / 60);
    },
    seconds() {
      return this.examForm.countdown % 60;
    },
  },
  mounted() {
    this.startCountdown();
  },
  beforeDestroy() {
    clearInterval(this.countdownTimer);
  },
  data() {
    return {
      radioValue: '',
      countdownTimer: null,
      dialogFormVisible: false,
      examForm: {
        title: "",
        countdown: 100 * 60,
        fly_exam_id: 0,
        other_paper_list: [
          //   {
          //     "id": "1",
          //     "questionType": "xz",
          //     "answer": "",
          //     "content": "1",
          //     "choice_a": "A",
          //     "choice_b": "B",
          //     "choice_c": "C",
          //     "choice_d": "D",
          //   }, {
          //     "id": "2",
          //     "questionType": "mxz",
          //     "answers": ["A", "B", "C"],
          //     "content": "2",
          //     "choice_a": "A1",
          //     "choice_b": "B1",
          //     "choice_c": "C1",
          //     "choice_d": "D1",
          //   }
          // ],
          // tks: [
          //   {
          //     id: 1,
          //     tk_num: 3,
          //     blanks: [
          //       { type: "text", value: "确认故障操作对象的上联端口已关闭，先接" },
          //       { type: "input", value: "" },
          //       { type: "text", value: "，再" },
          //       { type: "input", value: "" },
          //       { type: "text", value: "（注意先后顺序）。通知NOC网络工程师上线检查热备交换机。" },
          //     ],
          //   },
          //   {
          //     id: 2,
          //     tk_num: 3,
          //     blanks: [
          //       { type: "text", value: "确认故障操作对象的上联端口已关闭，先接" },
          //       { type: "input", value: "" },
          //       { type: "text", value: "，再" },
          //       { type: "input", value: "" },
          //       { type: "text", value: "（注意先后顺序）。通知NOC网络工程师上线检查热备交换机。" },
          //     ],
          //   },
          // ],
          // jds: [
          //   {
          //     "content": "事件/故障通报时限要求和流程说明",
          //     "answer": "",
          //   }
        ],
        tk_paper_list: [
          // {
          //   id: 2,
          //   tk_num: 3,
          //   blanks: [
          //     { type: "text", value: "确认故障操作对象的上联端口已关闭，先接" },
          //     { type: "input", value: "" },
          //     { type: "text", value: "，再" },
          //     { type: "input", value: "" },
          //     { type: "text", value: "（注意先后顺序）。通知NOC网络工程师上线检查热备交换机。" },
          //   ],
          // },
        ],
        jd_paper_list: [
          // {
          //   "content": "事件/故障通报时限要求和流程说明",
          //   "jd_examinee_answer": "",
          // }
        ],
      },
      formLabelWidth: '120px',
      dialogFormVisible: false,
      title: "",
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 5,
      },
      tableData: [
        // {
        //   id: "1",
        //   subject: "杭州飞检",
        // },
        // {
        //   id: "2",
        //   subject: "贵安基础设施",
        // },
      ],
    };
  },
};
</script>

<style>
body {
  user-select: none;
  /* 禁止用户选择文本 */
}

.no-copy-paste {
  user-select: none;
}

.centered-text {
  text-align: center;
  /* display: block; */
}

.center {
  display: inline-block;
  text-align: left;
}

.left-span {
  /* text-align: left; */
  display: block;
}

.option {
  white-space: pre-wrap;
  max-width: 1400px;
}


.option-wrapper {
  display: inline-block;
  vertical-align: top;
  margin-top: -15px;
}
</style>